package com.chen.pay.service.impl;

import com.chen.pay.dao.PayInfoMapper;
import com.chen.pay.enums.PayPlatformEnum;
import com.chen.pay.pojo.PayInfo;
import com.chen.pay.service.IPayService;
import com.lly835.bestpay.enums.BestPayPlatformEnum;
import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.enums.OrderStatusEnum;
import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.service.BestPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Slf4j
@Service
public class PayService implements IPayService {

    @Autowired
    private BestPayService bestPayService;

    @Autowired
    private PayInfoMapper payInfoMapper;

    /**
     * 创建/发起支付
     * @param orderId 订单号
     * @param amount 交易金额
     */
    @Override
    public PayResponse create(String orderId, BigDecimal amount, BestPayTypeEnum bestPayTypeEnum) {
        // 写入数据库
        PayInfo payInfo = new PayInfo(Long.parseLong(orderId),
                PayPlatformEnum.getByBestPayTypeEnum(bestPayTypeEnum).getCode(),
                OrderStatusEnum.NOTPAY.name(),
                amount);
        payInfoMapper.insert(payInfo);


        // 发起支付
        PayRequest payRequest = new PayRequest();
        // 设置订单名称格式
        payRequest.setOrderName("4559066-最好的支付sdk");
        // 设置订单id
        payRequest.setOrderId(orderId);
        // 设置订单金额
        payRequest.setOrderAmount(amount.doubleValue());
        // 设置支付类型
        payRequest.setPayTypeEnum(bestPayTypeEnum);

        PayResponse payResponse = bestPayService.pay(payRequest);
        // 打印日志
        log.info("payResponse={}", payResponse);

        return payResponse;
    }

    /**
     * 异步通知处理
     * @param notifyData
     */
    @Override
    public String asyncNotify(String notifyData) {
        // 1、签名校验
        PayResponse payResponse = bestPayService.asyncNotify(notifyData);
        log.info("payResponse={}", payResponse);
        // 2、金额校验（从数据库中查订单）
        // 3、修改订单支付状态
        // 4、告诉微信别再发通知了
        if (payResponse.getPayPlatformEnum() == BestPayPlatformEnum.WX) {
            return "<xml>\n" +
                    "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                    "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                    "</xml>";
        } else if (payResponse.getPayPlatformEnum() == BestPayPlatformEnum.ALIPAY) {// 告诉支付宝别再发通知了
            return "success";
        }
        throw new RuntimeException("异步通知中错误的平台");

    }
}
